//
//  RootViewController.m
//  123Mua_Modules
//
//  Created by duong nguyen on 11/3/12.
//  Copyright (c) 2012 uit. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController
@synthesize categoryArray,indexToCollapse,isDuplicated,gestureUp,gestureDown;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadCategoryData];
    [self.tableView setRowHeight:80];
    
    //Swipe
    self.gestureDown=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGestureRecognize:)];
    self.gestureDown.direction=UISwipeGestureRecognizerDirectionDown;
    [self.tableView addGestureRecognizer:self.gestureDown];
    self.gestureUp=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGestureRecognize:)];
    self.gestureUp.direction=UISwipeGestureRecognizerDirectionUp;
    [self.tableView addGestureRecognizer:self.gestureUp];
    
}

-(IBAction)handleSwipeGestureRecognize:(UISwipeGestureRecognizer *)recognizer{
    //CGPoint location=[self.swipeGetstureRecognizer locationInView:self.view];
    switch (recognizer.direction) {
        case UISwipeGestureRecognizerDirectionDown:
            [UIView animateWithDuration:0.5 delay:0.0 
                                options:UIViewAnimationOptionCurveEaseInOut 
                             animations:^{
                                 self.tabBarController.tabBar.center=CGPointMake(160, 505);
                             } completion:nil];
            
            break;
        case UISwipeGestureRecognizerDirectionUp:
            [UIView animateWithDuration:0.5 delay:0.0 
                                options:UIViewAnimationOptionCurveEaseInOut 
                             animations:^{
                                 self.tabBarController.tabBar.center=CGPointMake(160, 455);
                             } completion:nil];
            
            break;
        default:
            break;
    }
}

-(void)loadCategoryData{
    indexToCollapse=-1;
    isDuplicated=false;
    self.categoryArray=[[NSMutableArray alloc]init];
    for (int i=0; i<10; i++) {
        CategoryModel *model=[[CategoryModel alloc]init];
        model.name=[NSString stringWithFormat:@"Cate :%i",i];
        model.level=0;
        model.isSelected=false;
        model.subCategories=[[NSMutableArray alloc]init];
        model.accessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow.png"]];
        for (int j=0; j<3; j++) {
            CategoryModel *subCate=[[CategoryModel alloc]init];
            subCate.name=[NSString stringWithFormat:@"SubCate :%i",j];
            subCate.level=4;
            subCate.isSelected=false;
            subCate.subCategories=nil;
            subCate.accessoryView=nil;
            [model.subCategories addObject:subCate];
        }
        [self.categoryArray addObject:model];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.categoryArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
    
    // Configure the cell...

    cell.textLabel.text=[[self.categoryArray objectAtIndex:indexPath.row]name];
    cell.indentationLevel=[[self.categoryArray objectAtIndex:indexPath.row]level];
    [tableView setSeparatorStyle:UITableViewCellEditingStyleNone];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.accessoryView=[[self.categoryArray objectAtIndex:indexPath.row]accessoryView];
    
    UIView *view=[[[UIView alloc]initWithFrame:CGRectMake(5, 0, 310, 0.5)]autorelease];
    [view setBackgroundColor:[UIColor colorWithRed:232.f/255 green:232.f/255 blue:232.f/225 alpha:1]];

    if (cell.indentationLevel==0) {
      //  cell.textLabel.text=[[self.categoryArray objectAtIndex:indexPath.row]name];
        [cell.imageView setImage:[UIImage imageNamed:@"ic_mypham.png"]];
        
    }else {
        //UIView *view=[[[UIView alloc]initWithFrame:CGRectMake(20, 0, 280, 0.5)]autorelease];
        view.frame=CGRectMake(50, 0, 280, 0.5);
        [cell.imageView setImage:[UIImage imageNamed:@"arrow.png"]];
        
    }
    [cell.contentView addSubview:view];
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    CategoryModel *model=[self.categoryArray objectAtIndex:indexPath.row];
    if (model.level==0) {
        if (indexPath.row!=indexToCollapse && indexToCollapse >-1) {
            CategoryModel *model1=[self.categoryArray objectAtIndex:indexToCollapse];
            if ((model1.isSelected==true) && (model1.level==0)) {
                
                [self miniMizeRow:model1];
                //indexToCollapse=-1;
                [self.tableView reloadData];
                isDuplicated=true;
            }
        }

        if (model.isSelected) {
            // MiniMize
            [self miniMizeRow:model];
        }else {
           
            //Expand
            [self accessoryViewAnimation:model withRotate:7.85];
            NSUInteger count=indexPath.row+1;
            if (isDuplicated && indexPath.row>indexToCollapse && count>3) {
                count=count-3;
                isDuplicated=false;
            }
            indexToCollapse=count-1;
            NSMutableArray *arr=[NSMutableArray array];
            for (int i=0; i<model.subCategories.count; i++) {
                [arr addObject:[NSIndexPath indexPathForRow:count inSection:0]];
                [self.categoryArray insertObject:[model.subCategories objectAtIndex:i] atIndex:count++];
            }
            
            [self.tableView insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationBottom];
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexToCollapse inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            model.isSelected=true;
        }
    }
    
}

-(void) miniMizeRow:(CategoryModel *)model{
    [self accessoryViewAnimation:model withRotate:6.28];
    for (int i=0; i<model.subCategories.count; i++) {
        NSInteger indexToMove=[self.categoryArray indexOfObjectIdenticalTo:[model.subCategories objectAtIndex:i]];
        // NSLog(@"Index to move:%i",indexToMove);
        if (indexToMove!=NSNotFound) {
            [self.categoryArray removeObjectIdenticalTo:[model.subCategories objectAtIndex:i]];
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexToMove inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        }
    }

    model.isSelected=false;
}

-(void) accessoryViewAnimation:(CategoryModel *)model withRotate:(float) radian{
    [UIView animateWithDuration:0.5 
            delay:0 
            options:UIViewAnimationOptionCurveEaseIn 
            animations:^{
                model.accessoryView.transform=CGAffineTransformMakeRotation(radian);
    } completion:nil];
}
@end
